<!--
 * @Description: In User Settings Edit
 * @Author: gyc
 * @Date: 2019-09-12 21:35:46
 * @LastEditTime: 2019-10-06 15:19:34
 * @LastEditors: Please set LastEditors
 -->
<template>
  <Row class="mo-login-row">
    <Col :lg="{span:16,offset:4}" class="login-col">
      <div class="login">
        <div class="select-ctl">
          <div class="title">加入我们1</div>
          <div @click="goInedx">
            <AniSelect></AniSelect>
          </div>
        </div>
        <div class="login-main">
          <div class="login-logo">
            <img :src="imgURL" alt="111" />
            <input type="file" @change="testClick" />
          </div>

          <input
            type="text"
            placeholder="用户名"
            onkeyup="value=value.replace(/[\W]/g,'')"
            v-if="islogin"
            v-model="luser"
          />
          <input type="password" placeholder="密码" v-if="islogin" v-model="lpwd" />
          <input
            type="text"
            placeholder="用户名"
            @blur="testUser"
            v-model="username"
            v-if="!islogin"
            onKeyUp="value=value.replace(/[\W]/g,'')"
          />
          <input type="password" placeholder="密码" v-if="!islogin" v-model="pwd1" />
          <input type="password" placeholder="确认密码" v-if="!islogin" v-model="pwd2" />
          <div class="yanz">
            <label>验证码:</label>
            <input type="text" placeholder="验证码" v-model="lyanz" />
            <canvas class="yanz-canvas" id="myCanvas" height="22" width="44"></canvas>
          </div>
          <div class="login-main-ctl">
            <button v-if="islogin" @click="goLogin">登录</button>
            <button v-if="!islogin" @click="goRegister">注册</button>
          </div>
          <div class="register" v-if="islogin">
            还没有账号，赶紧来
            <a @click="register">快速注册</a>吧？
          </div>
          <div class="register" v-if="!islogin">
            已有账号，赶紧来
            <a @click="login">登录</a>吧？
          </div>
        </div>
      </div>
    </Col>
  </Row>
</template>

<script>
import $ from "jquery";
import { setTimeout } from "timers";
import aniSelect from "../anime/select/select";
import encrypt from "@/config/encrypt";
import { async } from "q";
export default {
  name: "moLogin",
  data() {
    return {
      islogin: true,
      number1: Math.round(Math.random() * 9),
      number2: Math.round(Math.random() * 9),
      username: "",
      luser: "",
      lpwd: "",
      lyanz: "",
      pwd1: "",
      pwd2: "",
      imgURL: require("../../../assets/logo.png"),
      upImgURL: "111",
      imgFile: "111",
      imgFileReader: ""
    };
  },
  created() {},
  mounted() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.font = "14px Arial";
    ctx.fillText(this.number1 + "+" + this.number2 + "=", 0, 16);
  },
  methods: {
    register: function() {
      this.islogin = false;
    },
    login: function() {
      this.islogin = true;
    },
    goInedx: function() {
      this.$router.push("/");
    },
    //测试用户名
    testUser: function() {
      this.$axios
        .get(this.$store.getters.url + "/testUser?user=" + this.username)
        .then(res => {
          // alert(res.data);
          if (!!res.data.data == false) {
            this.$Message.success("用户名可使用！");
          } else {
            this.$Message.error("用户名已存在，请更换用户名！");
            this.username = "";
          }
        });
    },
    //登录
    goLogin: function() {
      var _this = this;
      let key = "1314"; //设置密钥
      // this.ruleForm.password = encrypt.Encrypt(this.ruleForm.password, key); //加密
      let user = this.luser;
      let pwd = this.lpwd;
      // let psd = encrypt.Decrypt(this.ruleForm.password, key); //解密
      if (
        !!this.luser &&
        !!this.lpwd &&
        this.lyanz == this.number1 + this.number2
      ) {
        this.$axios
          .get(this.$store.getters.url + "/login", {
            params: {
              user: encrypt.Encrypt(user, key),
              pwd: encrypt.Encrypt(pwd, key)
            }
          })
          .then(res => {
            console.log(res.data);

            if (res.data.code == 200) {
              this.$store.dispatch("nowLogins");
              this.$Message.success("登陆成功！");
              this.$router.push("/");
              localStorage.setItem("loginfo1", "true");
              localStorage.setItem("loginfo2", res.data.data.id);
              setTimeout(() => {
                document.location.reload();
              }, 300);
            } else if (res.data.code == 201) {
              this.$Message.info("账号密码错误！");
            } else if (res.data.code == 202) {
              this.$Message.info("账号处于封停状态！");
            }
          });
      } else {
        this.$Message.info("请仔细检查！");
      }
    },
    //注册账号
    goRegister: function() {
      if (
        this.username != "" &&
        this.pwd1 != "" &&
        this.pwd2 != "" &&
        this.pwd1 === this.pwd2 &&
        this.lyanz == this.number1 + this.number2
      ) {
        this.$axios
          .get(this.$store.getters.url + "/register", {
            params: {
              user: this.username,
              pwd: this.pwd1,
              avatar: this.imgFile.name
            }
          })
          .then(res => {
            console.log(res.data);
            if (res.data.code == "201") {
              this.$Message.error("用户名已存在！");
            } else if (res.data.code == "200") {
              //通过FormData构造函数创建一个空对象
              var formdata = new FormData();
              //可以通过append()方法来追加数据
              formdata.append("file", this.imgFile);
              formdata.append("name", this.imgFile.name);
              console.log(formdata.get("file"), "gggggg"); //laotie
              const config = {
                headers: { "Content-Type": "multipart/form-data" }
              };
              this.$axios.post(
                this.$store.getters.url + "/upload",
                formdata,
                config
              );
              this.$Message.info("注册成功！");
              window.location.reload();
            }
          });
      } else {
        this.$Message.info("信息不完全/密码两次输入一致！");
      }
    },
    testClick: function(e) {
      if (window.FileReader) {
        // var fr = new FileReader();
        // add your code here
      } else {
        alert("Not supported by your browser!");
      }
      var files = e.target.files,
        file;
      if (files && files.length > 0) {
        // 获取目前上传的文件
        this.imgFile = file = files[0];
        // 来在控制台看看到底这个对象是什么
        console.log(file);
        // 那么我们可以做一下诸如文件大小校验的动作
        if (file.size > 1024 * 1024 * 2) {
          alert("图片大小不能超过 2MB!");
          return false;
        }
        // !!!!!!
        // 下面是关键的关键，通过这个 file 对象生成一个可用的图像 URL
        // 获取 window 的 URL 工具
        var URL = window.URL || window.webkitURL;
        // 通过 file 生成目标 url
        var imgURL = URL.createObjectURL(file);

        var reader = new FileReader();
        reader.readAsBinaryString(file);
        reader.onload = function() {
          console.log(this.result);
          //读取完毕后输出结果
          this.imgFileReader = this.result;
        };

        this.imgURL = imgURL;
      }
    }
  },
  components: {
    AniSelect: aniSelect
  }
};
</script>

<style lang="scss" scoped>
$hoverColor: rgb(221, 221, 221);
.mo-login-row {
  position: absolute;
  width: 100%;
  height: 100%;
}
.login-col {
  display: flex;
  height: inherit;
  justify-content: center;
  align-items: center;
}
.login {
  display: flex;
  width: 300px;
  height: 450px;
  background-color: white;
  transition: height 0.4s;
  flex-direction: column;
  // box-shadow: 2px 2px 6px #ccc;
}
.select-ctl {
  display: flex;
  width: 100%;
  height: 31px;
  justify-content: space-between;
  border-bottom: 1px solid $hoverColor;
  .title {
    display: flex;
    justify-content: center;
    align-items: center;
    padding-left: 8px;
  }
}
.login-main {
  display: flex;
  display: flexbox;
  width: 100%;
  flex: 1;
  flex-direction: column;
  align-items: center;
  justify-content: space-evenly;
  .login-logo {
    display: flex;
    img {
      width: 50px;
      height: 50px;
      border-radius: 25px;
      box-shadow: 0px 0px 10px rgb(161, 161, 161);
    }
    input {
      position: absolute;
      width: 50px;
      height: 50px;
      opacity: 0;
      outline: none;
      cursor: pointer;
    }
  }
  img {
    width: 50px;
    height: 50px;
    border-radius: 25px;
    box-shadow: 0px 0px 10px rgb(161, 161, 161);
  }
  input {
    width: 150px;
    height: 22px;
    padding-left: 2px;
  }
  .login-main-ctl {
    button {
      width: 150px;
      height: 25px;
      background-color: rgb(161, 161, 161);
      outline: none;
      border: 0px;
      color: white;
      cursor: pointer;
      transition: background-color 0.4s;
      &:hover {
        background-color: rgb(51, 51, 51);
      }
    }
  }
  .yanz {
    display: flex;
    label {
      display: inline-flex;
      width: 50px;
      height: 22px;
      align-items: center;
      font-size: 12px;
    }
    input {
      width: 48px;
      margin-right: 10px;
    }
    .yanz-canvas {
      height: 22px;
      width: 40px;
    }
  }
}
</style>